import React, { FC } from 'react';
import { getDisplayName } from '@/utils/index';

export interface ThemeProps {
  primary?: string;
  secondary?: string;
}

/**
 * 高阶组件——给组件注入主题
 * @param Component
 * 泛型 P表示传递到 HOC 的组件的 props
 * React.ComponentType<P> 定义传递到 HOC 的组件的类型，可以是类组件或者是函数组件
 * 是 React.FunctionComponent<P> | React.ClassComponent<P>的别名
 */
function withTheme<P>(Component: React.ComponentType<P & ThemeProps>) {
  /**
   * 高阶组件的props
   */
  type WithThemeProps = P;

  const WithTheme = (props: WithThemeProps) => {
    const theme: ThemeProps = {
      primary: 'red',
      secondary: 'blue',
    };

    return <Component {...theme} {...props} />;
  };
  WithTheme.displayName = `withTheme${getDisplayName(Component)}`;

  return WithTheme;
}

const Demo8: FC<ThemeProps> = props => {
  return (
    <div>
      <div style={{ color: props.primary }}>primary高阶组件</div>
      <div style={{ color: props.secondary }}>secondary高阶组件</div>
    </div>
  );
};

export default withTheme(Demo8);
